﻿using Module_Debug.socket;
using Module_Debug.VESADSCTool;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;


namespace Module_Debug
{
    public partial class UDP_RCH : Form
    {
        private byte[] Send_buf = new byte[1];
        frmMain frmTop = null;
        CRC16 CRCData = new CRC16();
        public DSCToos frmVESADSCTool;
        public UDP_RCH(frmMain SX_UDP_RCH)
        {
            frmTop = SX_UDP_RCH;
            InitializeComponent();
            frmTop.Child_window_hide_already = true;
            frmTop.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体 
            string[] s = { ".bmp" };
            this.ImageType = new List<string>(s);

        }

        Int16 num = 0;
        void ShowMsg(string str)//log
        {
            txttip.AppendText(str + "\r\n");//--------------------------------
            num++;
            if (num % 4 == 0) txttip.BackColor = Color.FromArgb(255, 128, 128);
            else if (num % 4 == 1) txttip.BackColor = Color.FromArgb(255, 255, 128);
            else if (num % 4 == 2) txttip.BackColor = Color.FromArgb(128, 255, 255);
            else if (num % 4 == 3) txttip.BackColor = Color.FromArgb(128, 255, 128);
            else txttip.BackColor = Color.FromArgb(255, 255, 128);
        }


        private void UDP_RCH_Load(object sender, EventArgs e)
        {
        }

        #region  UDP
        //发送
        //对方地址
        private static readonly IPAddress MulticastAddress = IPAddress.Parse("192.168.1.1");
        private const int MulticastPort = 8080;
        //本机地址
        //public const int ListenPort = 8090;
        //public readonly IPAddress ListenAddress = IPAddress.Parse("192.168.1.1");
        //groupEP = new IPEndPoint(ListenAddress, ListenPort);
        //udpClient = new UdpClient(groupEP);

        public static UdpClient MulticastudpClient;

        public void SendCallback(byte[] sendByte)
        {
            IPEndPoint target = new IPEndPoint(MulticastAddress, MulticastPort);
            //发送数据到远程主机
            udpClient.Send(sendByte, sendByte.Length, target);

            //连接到子网广播地址并指定接收端口
            //udpClient.Connect(target);
            //udpClient.Send(sendByte, sendByte.Length);
            //udpClient.Close();
        }


        //接收
        //public class UdpReceiver
        //{
        //    //监听地址
        //    //private static readonly IPAddress ListenAddress = IPAddress.Parse("192.168.1.1");
        //    private const int ListenPort = 8080;
        //    public string ReceiveData(int port)
        //    {
        //        UdpClient client = new UdpClient(port);
        //        IPEndPoint source = new IPEndPoint(IPAddress.Any, ListenPort);
        //        byte[] data = client.Receive(ref source);

        //        return Encoding.UTF8.GetString(data);
        //    }
        //}
        //监听
        public byte[] buffer = new byte[3840 * 2160 * 3 * 10];
        public int buffer_length = 0;
        public static List<byte[]> Listenerlist = new List<byte[]>();
        public static int Receive_flag_bit = 0;
        public static List<byte[]> Sendlist = new List<byte[]>();
        public static UdpClient udpClient;
        public static IPEndPoint groupEP;
        public const int ListenPort = 8080;
        public readonly IPAddress ListenAddress = IPAddress.Parse("192.168.1.1");
        //public class UdpListener
        //{

        //public List<byte[]> Listenerlist;
        //初始化一次
        //public UdpListener()
        //{
        //    // 设置监听的UDP端口
        //    //this.groupEP = new IPEndPoint(ListenAddress, ListenPort);
        //    //this.udpClient = new UdpClient(this.groupEP);
        //}
        public void UdpListenerinitialize()
        {
            // 设置监听的UDP端口
            groupEP = new IPEndPoint(ListenAddress, ListenPort);
            udpClient = new UdpClient(groupEP);
        }
        //开始监听
        public void StartListening()
        {
            // Console.WriteLine("Listening for UDP data on port 11000...");

            // 开始异步接收数据
            udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null);
        }

        public void ReceiveCallback(IAsyncResult ar)
        {
            // 结束异步接收
            byte[] receiveBytes = udpClient.EndReceive(ar, ref groupEP);
            //string receiveString = Encoding.ASCII.GetString(receiveBytes);
            Receive_flag_bit = 1;
            int length = receiveBytes.Length;
            Buffer.BlockCopy(receiveBytes, 0, buffer, buffer_length, length);
            buffer_length += length;
            //public byte[] buffer = new byte[3840 * 2160 * 3 * 2];
            //public int buffer_length = 0;
            //Listenerlist.Add(receiveBytes);//缓存 
            //Console.WriteLine("Received: {0}", receiveString);
            // 再次开始接收
            udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null);

            //发送数据到远程主机
            //string sendString = "Hello, Client!";
            //byte[] sendBytes = Encoding.ASCII.GetBytes(sendString);
            //udpClient.Send(sendBytes, sendBytes.Length, groupEP);
        }
        //public void SendCallback(byte[] sendByte)
        //{
        //    //发送数据到远程主机
        //    udpClient.Send(sendByte, sendByte.Length, groupEP);

        //}

        //static void Main(string[] args)
        //{
        //    UdpListener listener = new UdpListener();
        //    listener.StartListening();
        //}
        //}

        bool UDPinitialize = false;
        private void button_Listener_Click(object sender, EventArgs e)
        {
            if (UDPinitialize == false)
            {
                UDPinitialize = true;
                //只初始化一次
                UdpListenerinitialize();
                //一直监听中
                StartListening();
            }
            else
            {
                MessageBox.Show("无需再次初始化");
            }


        }
        string IP_out_BMP_path = "";//路径+BMP明
        private void button_RX_Click(object sender, EventArgs e)
        {
            if (Receive_flag_bit == 1)
            {
                if (radio_showHEX.Checked == true)
                {
                    byte[] binchar = new byte[buffer_length];
                    Buffer.BlockCopy(buffer, 0, binchar, 0, buffer_length);
                    if (buffer_length > (int)length.Value)
                    {
                        using (BinaryWriter binaryWriter = new BinaryWriter(File.Open("UDP接收.bin", FileMode.Create)))
                        {
                            //Write(byte[] buffer, int index, int count);
                            binaryWriter.Write(binchar);
                        }
                        MessageBox.Show("bin接收完成！文件：UDP接收.bin");
                    }
                    else
                    {
                        string receiveString = String.Join("\r\n", Array.ConvertAll(binchar, b => b.ToString("x2")));
                        textBox_RX.Text += receiveString;
                    }
                }
                else if (radio_BMP.Checked == true)//保存BMP
                {
                    int bmp_h = H_P_True;
                    int bmp_v = V_P_True;
                    if (checkBox_scaling_UDP.Checked == true)
                    {
                        bmp_h = (int)HACT.Value;
                        bmp_v = (int)VACT.Value;
                    }
                    byte[] binchar = new byte[bmp_h * bmp_v * 3];
                    Buffer.BlockCopy(buffer, 0, binchar, 0, buffer_length);

                    Bitmap bt_imgBacktemp = new Bitmap(bmp_h, bmp_v, PixelFormat.Format24bppRgb);
                    //int length = 0;
                    if (radio_8bit.Checked == true)
                    {
                        //for (int hang = 0; hang < bmp_v; hang++)
                        //{
                        //    for (int lie = 0; lie < bmp_h; lie++)
                        //    {
                        //        bt_imgBacktemp.SetPixel(lie, hang, Color.FromArgb(binchar[length * 3], binchar[length * 3 + 1], binchar[length * 3 + 2]));
                        //        length++;
                        //    }
                        //}
                        // bt_imgBacktemp.Save("UDP接收.BMP", ImageFormat.Bmp);
                        Bitmap bitmapImage = buildBMP(bmp_h, bmp_v, binchar);
                        if((defaultfilePath!= "")&&(BMP_name!=""))
                        {
                            if (Directory.Exists(defaultfilePath + "\\IP_out") == false)//如果不存在就创建file文件夹
                            {
                                Directory.CreateDirectory(defaultfilePath + "\\IP_out");
                            }
                            IP_out_BMP_path = defaultfilePath + "\\IP_out\\IP_out" + BMP_name;
                            bitmapImage.Save(IP_out_BMP_path, ImageFormat.Bmp);

                            if ((IP_OUT_Send.Checked == true)&&(UDP_Rrogram.UDP_VESA_sign == 0))
                            {
                                path_2KS = defaultfilePath + "\\IP_out";
                                DirectoryInfo di = new DirectoryInfo(path_2KS);
                                //listBox3_BMPFile.Items.Clear();
                                CreateListItem(di);//递归加载文件夹里的所有图片
                                txtbmp.Text = path_2KS;
                                send_BMP_2KS(IP_out_BMP_path);
                            }
                            else if(UDP_Rrogram.UDP_VESA_sign == 1)
                            {
                                UDP_Rrogram.UDP_BMP_in_path = IP_out_BMP_path;
                                //UDP_VESA_sign=1开启等待，=2开始压缩，=3压缩完成，=1继续等待，=0不开压缩
                                UDP_Rrogram.UDP_VESA_sign = 2;
                                DateTime currentTime = DateTime.Now;
                                string tt = "开始压缩" + currentTime.Minute.ToString() + "分；" + currentTime.Second.ToString() + "秒；" + currentTime.Millisecond.ToString() + "毫秒；\r\n";
                                ShowMsg(tt);
                            }

                        }
                        bitmapImage.Save("UDP接收.BMP", ImageFormat.Bmp);

                    }
                    else
                    {
                        MessageBox.Show("16bit请保存bin");
                    }
                }
                else//文本
                {
                    // 使用UTF8编码将byte数组转换为String
                    string receiveString = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer_length);

                    //int count = 0;
                    ////遍历List<int>
                    //foreach (byte[] i in Listenerlist)
                    //{
                    //    receiveString+= Encoding.ASCII.GetString(i);
                    //    count++;
                    //}
                    if (buffer_length > (int)length.Value)
                    {
                        StreamWriter sw = new StreamWriter("UDP接收.dat");
                        sw.WriteLine(receiveString);
                        //sw.WriteLine( (char[]) binchar);
                        sw.Close();
                        MessageBox.Show("接收完成！文件：UDP接收.dat");
                    }
                    else
                    {
                        textBox_RX.Text += receiveString;
                    }
                }

                ShowMsg("接收长度" + buffer_length.ToString());
                Receive_flag_bit = 0;
                buffer_length = 0;
                // Listenerlist.Clear();//删除 重新加载
            }
            else
            {
                ShowMsg("未更新数据");
            }
        }

        private void button_TX_Click(object sender, EventArgs e)
        {
            string strCon = textBox_TX.Text;
            byte[] byteArray;
            int LUT_len = 10000;
            if (radio_HEX.Checked == true)
            {
                try
                {
                    strCon = strCon.Replace("\n", " ");
                    strCon = strCon.Replace("\r", "");
                    //strCon = strCon.Substring(0, strCon.Length - 1);
                    byteArray = strCon.Split(' ').Select(temp => "0x" + temp).Select(temp => (byte)Convert.ToInt32(temp, 16)).ToArray();
                }
                catch
                {
                    MessageBox.Show("格式错误，删除注释和非法字符");
                    return;
                }
            }
            else
                byteArray = Encoding.UTF8.GetBytes(strCon);
            LUT_len = byteArray.Length;

            //只初始化一次
            if (LUT_len < (int)length.Value) SendCallback(byteArray);
            else MessageBox.Show("数据太长，请使用超长包发送");
        }

        private void button_clear_Click(object sender, EventArgs e)
        {
            txttip.Clear();
            textBox_TX.Clear();
            textBox_RX.Clear();
        }

        private void txt_send_Click(object sender, EventArgs e)
        {

            string path_txt = SD5502H_txt.Text;
            var strCon = string.Empty;
            string contentPath = path_txt;
            byte[] originalBytes;
            if (radio_SendHex.Checked == true)
            {

                #region 二进制读取

                //文件流类//用于文件的读写与关闭//来自于System.IO 
                FileStream fileStream = new FileStream(contentPath, FileMode.Open);
                //读二进制文件类
                BinaryReader br = new BinaryReader(fileStream, Encoding.UTF8);
                //获取bin文件长度
                int file_len = (int)fileStream.Length;
                //得到所有字节
                originalBytes = br.ReadBytes(file_len);
                //关闭 BinaryReader 对象和基础流
                br.Dispose(); //释放资源
                br.Close(); //关闭数据流
                #endregion
            }
            else
            {
                StreamReader sr1 = new StreamReader(contentPath, Encoding.UTF8);
                strCon = sr1.ReadToEnd();
                sr1.Close();
                //strCon = strCon.Replace("\n", "");
                //strCon = strCon.Replace("\r", "");
                //StreamWriter sw = new StreamWriter("UDP测试.dat");
                //sw.WriteLine(strCon);
                ////sw.WriteLine( (char[]) binchar);
                //sw.Close();
                //MessageBox.Show("去掉空格后 UDP测试.dat");
                // 原始的字节数组
                originalBytes = Encoding.UTF8.GetBytes(strCon);
            }
            line_buffer_Send(originalBytes);
        }
        void line_buffer_Send(byte[] originalBytes)
        {
            progressBar1_UDP.Value = 0;
            label14_UDP.Text = progressBar1_UDP.Value.ToString() + "%";
            Application.DoEvents();
            int splitSize = (int)length.Value; // 每次分割的大小为1700或32000
            double delay_us = (double)delay_ms1.Value;
            DateTime currentTime = DateTime.Now;
            string tt = "开始" + currentTime.Minute.ToString() + "分；" + currentTime.Second.ToString() + "秒；" + currentTime.Millisecond.ToString() + "毫秒；\r\n";
            ShowMsg(tt);
            int buffer_length = originalBytes.Length;
            ShowMsg("发送长度" + buffer_length.ToString());
            for (int i = 0; i < buffer_length; i += splitSize)
            {
                int remainingCount = Math.Min(splitSize, buffer_length - i);

                byte[] tempBytes = new byte[remainingCount];
                Array.Copy(originalBytes, i, tempBytes, 0, remainingCount);
                SendCallback(tempBytes);
                delayUs(delay_us);
                progressBar1_UDP.Value = (i + splitSize) / (buffer_length / 100);
                label14_UDP.Text = progressBar1_UDP.Value.ToString() + "%";
                Application.DoEvents();
            }
            DateTime currentTime2 = DateTime.Now;
            string tt2 = "结束" + currentTime2.Minute.ToString() + "分；" + currentTime2.Second.ToString() + "秒；" + currentTime2.Millisecond.ToString() + "毫秒；\r\n";
            ShowMsg(tt2);
        }
        /*
    功能：微秒延时（1000us == 1ms）
    参数：延时时间单位ms
        延时5us：delayUs(0.005)；
*/
        public static double delayUs(double time)
        {
            System.Diagnostics.Stopwatch stopTime = new System.Diagnostics.Stopwatch();

            stopTime.Start();
            while (stopTime.Elapsed.TotalMilliseconds < time) { }
            stopTime.Stop();

            return stopTime.Elapsed.TotalMilliseconds;
        }

        #endregion

        #region  下发至UDP 图片
        private List<string> ImageType;
        public string defaultfilePath = ""; //图片路径
        string paths = ""; //路径+.BMP
        string BMP_name = ""; //BMP
        int H_P_True;
        int V_P_True;
        string[] paths_all = new string[100]; //BMP名
        int numbier = 0;
        private void btnBrowsePic_Click_UDP(object sender, EventArgs e)    //载入画面按键  选择文件夹
        {
            numbier = 0;
            if (textBox_PAN_UDP.Text != "")
            {
                defaultfilePath = textBox_PAN_UDP.Text;
            }
            else
            {
                StreamReader streamReader = new StreamReader("./update/Picaddr.txt", Encoding.Default);
                defaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (defaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = defaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            defaultfilePath = fldb.SelectedPath;
            if (!Directory.Exists(defaultfilePath))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            DirectoryInfo di = new DirectoryInfo(defaultfilePath);
            this.listBox3_BMPFile_UDP.Items.Clear();
            this.CreateListItem_UDP(di);//递归加载文件夹里的所有图片
            textBox_PAN_UDP.Text = defaultfilePath;
            // -------------------------------------------------------------------------
            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Picaddr.txt", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(defaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
        }
        private void CreateListItem_UDP(DirectoryInfo di)
        {
            foreach (DirectoryInfo childDi in di.GetDirectories())
            {
                this.CreateListItem_UDP(childDi);
            }
            foreach (FileInfo fi in di.GetFiles())
            {
                if (ImageType.Contains(fi.Extension))//找到一个图片(如果用户手贱把一个excel文件后缀改成jpeg没办法)
                {
                    this.listBox3_BMPFile_UDP.Items.Add(new MyImage(fi.FullName));
                    paths_all[numbier] = fi.Name;
                    numbier++;
                }
            }
        }
        public class MyImage
        {
            public MyImage(string p)
            {
                this.Path = p;
            }
            public string Path { get; set; }
            public override string ToString()
            {
                if (Path == null)
                {
                    return null;
                }
                return System.IO.Path.GetFileName(this.Path);
            }
        }
        private void lstImage_Click_UDP(object sender, EventArgs e)
        {
            if (listBox3_BMPFile_UDP.SelectedItem == null)
            {
                return;
            }
            paths = textBox_PAN_UDP.Text + '\\' + listBox3_BMPFile_UDP.SelectedItem.ToString();
            BMP_name= listBox3_BMPFile_UDP.SelectedItem.ToString();
            MyImage selectedImg = (MyImage)listBox3_BMPFile_UDP.SelectedItem;
            //Image img = new Bitmap(selectedImg.Path);
            //pictureBox1.Image = img;
            FileStream fileStream = new FileStream(selectedImg.Path, FileMode.Open, FileAccess.Read);
            pictureBox_UDP.Image = Image.FromStream(fileStream);
            fileStream.Close();
            fileStream.Dispose();

            FileStream aFile;
            //byte[] TemFileContent = new byte[1024 * 100];
            byte[] TemFileContent = new byte[512 * 4000 + 100];
            System.Int32 ByteReaded = 0x00;
            //string FileName = textBox_PAN.Text + '\\' + listBox3_BMPFile.SelectedItem.ToString();
            // aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            aFile = new FileStream(selectedImg.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            ByteReaded = aFile.Read(TemFileContent, 0, 54);
            H_P_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
            V_P_True = ((TemFileContent[23] << 8) + TemFileContent[22]);
            label_H.Text = H_P_True.ToString();
            label_V.Text = V_P_True.ToString();

        }

        private void textBox_PAN_KeyDown_UDP(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btnBrowsePic_Click_UDP(sender, e);
        }
        //下发图片
        //string paths = ""; //路径+.BMP
        Int64 BMP_buffer_length = 1234567989;
        int BMP_send_flag = 0;
        private void listBox3_BMPFile_DoubleClick(object sender, EventArgs e)
        {

            if (File.Exists(paths)) // 查找文件是否存在
            {
                Image imgBack = System.Drawing.Image.FromFile(paths);     //相框图片
                Bitmap bt_imgBacktemp = (Bitmap)imgBack; //产生对象
                int h = (int)HACT.Value;
                int v = (int)VACT.Value;
                if (checkBox_scaling_UDP.Checked == true)//按设置分辨率缩放
                {
                    // BMP 缩放
                    imgBack = resizeImage(bt_imgBacktemp, new Size(h, v));
                }
                bt_imgBacktemp = (Bitmap)imgBack; //产生对象
                int bmp_h = bt_imgBacktemp.Width;
                int bmp_v = bt_imgBacktemp.Height;
                //byte[] BMP_send = new byte[bmp_h * bmp_v*3];

                //int length = 0;
                //for (int hang = 0; hang < bmp_v; hang++)
                //{
                //    for (int lie = 0; lie < bmp_h; lie++)
                //    {
                //        Color color_1 = bt_imgBacktemp.GetPixel(lie, hang);//color
                //        BMP_send[length * 3] = color_1.R;
                //        BMP_send[length * 3+1] = color_1.G;
                //        BMP_send[length * 3+2] = color_1.B;
                //        length++;
                //    }
                //}
                //长包下发
                if(checkBox_UDP.Checked==true)
                {
                    button_parameter_Click(sender, e);
                    delayUs(5);
                }
                  byte[] BMP_send = BitmapToByteArray_BGR(bt_imgBacktemp);
                BMP_buffer_length = BMP_send.Length;
                BMP_send_flag = 1;//标志位
                Receive_flag_bit = 0;
                buffer_length = 0;
                line_buffer_Send(BMP_send);
            }
        }
        public static Bitmap buildBMP(int width, int height, byte[] imgBytes)
        {
            Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
             ImageLockMode.WriteOnly, bmp.PixelFormat);
            //用Marshal的Copy方法，将刚才得到的内存字节数组复制到BitmapData中
            System.Runtime.InteropServices.Marshal.Copy(imgBytes, 0, bmpData.Scan0, imgBytes.Length);
            //解锁内存区域  
            bmp.UnlockBits(bmpData);
            return bmp;
        }


        public byte[] BitmapToByteArray_BGR(Bitmap bitmap)
        {
            // 创建一个与位图宽度和高度对应的区域
            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            // 锁定内存区域
            BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

            // 获取图像数据的大小
            int size = bitmapData.Stride * bitmap.Height;
            byte[] bytes = new byte[size];

            // 拷贝内存数据到字节数组
            Marshal.Copy(bitmapData.Scan0, bytes, 0, size);

            // 解锁内存区域
            bitmap.UnlockBits(bitmapData);

            return bytes;
        }



        // BMP 缩放
        //Bitmap b = new Bitmap(2, 2, PixelFormat.Format24bppRgb);
        //Image new_b = resizeImage(b, new Size(200, 200));
        private static Image resizeImage(System.Drawing.Image imgToResize, Size size)
        {
            //获取图片宽度
            int sourceWidth = imgToResize.Width;
            //获取图片高度
            int sourceHeight = imgToResize.Height;
            //期望的宽度
            int destWidth = (int)size.Width;
            //期望的高度
            int destHeight = (int)size.Height;

            Bitmap b = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //绘制图像
            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
            return (System.Drawing.Image)b;
        }

        #endregion

        #region  下发至2KS 图片
        #region    //浏览图片
        string path_2KS = "";
        private void btnBrowsePic_Click(object sender, EventArgs e)    //载入画面按键  选择文件夹
        {
            if (txtbmp.Text != "")
            {
                frmTop.defaultfilePath = txtbmp.Text;
            }
            else
            {
                StreamReader streamReader = new StreamReader("./update/Picaddr.txt", Encoding.Default);
                frmTop.defaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (frmTop.defaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = frmTop.defaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            frmTop.defaultfilePath = fldb.SelectedPath;
            path_2KS = fldb.SelectedPath;
            if (!Directory.Exists(path_2KS))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }
            DirectoryInfo di = new DirectoryInfo(path_2KS);
            listBox3_BMPFile.Items.Clear();
            CreateListItem(di);//递归加载文件夹里的所有图片
            txtbmp.Text = path_2KS;
            // -------------------------------------------------------------------------
            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Picaddr.txt", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(frmTop.defaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
        }
        /// <summary>
        /// 递归文件夹，把文件夹里所有后缀类似图片的文件，加入listbox
        /// </summary>
        /// <param name="di"></param>
        private void CreateListItem(DirectoryInfo di)
        {
            listBox3_BMPFile.Items.Clear();
            foreach (DirectoryInfo childDi in di.GetDirectories())
            {
                this.CreateListItem(childDi);
            }

            foreach (FileInfo fi in di.GetFiles())
            {
                if (ImageType.Contains(fi.Extension))//找到一个图片(如果用户手贱把一个excel文件后缀改成jpeg没办法)
                {
                    this.listBox3_BMPFile.Items.Add(new MyImage(fi.FullName));
                }
            }
        }
        private void lstImage_Click(object sender, EventArgs e)
        {
            if (listBox3_BMPFile.SelectedItem == null)
            {
                return;
            }
            MyImage selectedImg = (MyImage)listBox3_BMPFile.SelectedItem;
            //Image img = new Bitmap(selectedImg.Path);
            //pictureBox1.Image = img;

            Image img;
            using (var bmpTemp = new Bitmap(selectedImg.Path))
            {
                img = new Bitmap(bmpTemp);
            }
            pictureBox1.Image = img;
            img = null;
        }
        private byte ircbmpflag = 1;
        private void btnPrevPic_Click(object sender, EventArgs e)
        {
            string FileName = "";
            FileName = txtbmp.Text + '\\' + listBox3_BMPFile.SelectedItem.ToString();
            send_BMP_2KS(FileName);
        }
        void send_BMP_2KS(string FileName)
        {
            Int32 HACT_True = 0;
            Int32 HACT_Skip = 0;
            Int32 VACT_True = 0;
            Int32 m_txlen = 0;
            Int32 j = 0;
            FileStream aFile;

            //byte[] TemFileContent = new byte[1024 * 100];
            byte[] TemFileContent = new byte[512 * 4000 + 100];
            System.Int32 ByteReaded = 0x00;
            if (checkBox_scaling_2KS.Checked)
            {

                Bitmap image1 = new Bitmap(FileName, true);
                int h = (int)HACT.Value;
                int v = (int)VACT.Value;
                // BMP 缩放
                Image imgBack = resizeImage(image1, new Size(h, v));

                imgBack.Save(@".\tempW2x.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                FileName = @".\tempW2x.bmp";
            }
            try
            {
                aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            }
            catch
            {
                MessageBox.Show("图片地址异常，请检查", "错误");
                return;
            }

            //aFile = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            ByteReaded = aFile.Read(TemFileContent, 0, 54);
            HACT_True = ((TemFileContent[19]) << 8) + TemFileContent[18];
            VACT_True = ((TemFileContent[23] << 8) + TemFileContent[22]);


            if ((frmTop.Dis_mode.SelectedIndex == 1)) //video
            {
                HACT_Skip = HACT_True % 10 > 0 ? (HACT_True + 10 - HACT_True % 10) : HACT_True;
            }
            else
            {
                HACT_Skip = HACT_True;
            }
            try
            { //5a a5 9DF0731A-----提前下个标志位告诉下位机开始送图了，避免特殊图片格式导致错误配置
                TemFileContent[0] = 0xbd; TemFileContent[1] = 0x5a; TemFileContent[2] = 0xa5; TemFileContent[3] = 0x9d; TemFileContent[4] = 0xf0;
                frmTop.comPort.Write(TemFileContent, 0, 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
            //-----------------------------------
            try
            {
                //HACT_True = Sig_mode.SelectedIndex > 2 ? Convert.ToInt32(2 * ((TemFileContent[19]<<8)+ TemFileContent[18])) : Convert.ToInt32((TemFileContent[19] << 8) + TemFileContent[18]);
                j = 1;
                while (j <= VACT_True)
                {


                    if (HACT_True % 4 != 0)
                        aFile.Seek((VACT_True - j) * (HACT_True * 3 + (HACT_True % 4)) + 54, SeekOrigin.Begin);
                    else
                        aFile.Seek((VACT_True - j) * HACT_True * 3 + 54, SeekOrigin.Begin);

                    ByteReaded = aFile.Read(TemFileContent, 0, HACT_True * 3); // 
                    try
                    {
                        frmTop.comPort.Write(TemFileContent, 0, HACT_Skip * 3);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                        break;
                    }
                    m_txlen += ByteReaded;
                    progressBar1.Value = Convert.ToInt32((double)m_txlen / aFile.Length * 100);
                    label_2KS.Text = progressBar1.Value.ToString() + "%";
                    Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                    j++;

                }

                TemFileContent[0] = 0x5A;
                try
                {
                    frmTop.comPort.Write(TemFileContent, 0, 1);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
                aFile.Close();
            }
            catch
            {
                txttip.Text += "啥图片都没显示";
                txttip.Select(txttip.Text.Length, 0);
                txttip.ScrollToCaret();
            }

        }
        private void txtbmp_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btnBrowsePic_Click(sender, e);
        }
        //public class MyImage
        //{
        //    public MyImage(string p)
        //    {
        //        this.Path = p;
        //    }
        //    public string Path { get; set; }
        //    public override string ToString()
        //    {
        //        if (Path == null)
        //        {
        //            return null;
        //        }
        //        return System.IO.Path.GetFileName(this.Path);
        //    }
        //}
        //-----------------------------------------
        #endregion


        #endregion

        #region  UDP协议
        //协议格式
        //  byte[10] cmd = { 0x7F, 0x00, 0x01, 0x02, 0x04, 0x01, 0x02, 0x03, 0x04, 0xcc };
        //  u8  flag=0x7f;
        //  u16 DestAddr=0x0001;//目标地址
        //  u8  Type=0x02;//指令
        //  u8  Length=0x04;
        //  u8  buf[100];
        //  u8  verify=0xcc;
        private void button_parameter_Click(object sender, EventArgs e)
        {
            Int64 h = (int)HACT.Value;
            Int64 v = (int)VACT.Value;
            Int64 dbv = (int)DBV_IN.Value;
            Int64 SPR = 0;
            if (RGBG_SENSE.Checked == true) SPR = 1;
            Int64 bit_width = 0;
            if (radio_8bit.Checked == true) bit_width = 8;
            else bit_width = 16;
            UInt64 bit_64bit_control = Convert.ToUInt64(control64bit.Text, 16);
            Int64 R = (int)numPatternR.Value;
            Int64 G = (int)numPatternG.Value;
            Int64 B = (int)numPatternB.Value;
            Int64 send_accept = 0;//是否 回传数据 标志位
            Button btnTmp;
            try
            {
                btnTmp = (Button)sender;
            }
            catch
            {
                btnTmp = new Button();//实体化一个按钮控件
                btnTmp.Name = "listBox3_BMPFile_UDP";
            }

            switch (btnTmp.Name)
            {
                case "button_parameter":
                    break;
                case "btnPatternW":
                    send_accept = 1;
                    break;
                case "btnred":
                    R = 255; G = 0; B = 0;
                    send_accept = 1;
                    break;
                case "btngreen":
                    R = 0; G = 255; B = 0;
                    send_accept = 1;
                    break;
                case "btnblue":
                    R = 0; G = 0; B = 255;
                    send_accept = 1;
                    break;
                case "btnwhite":
                    R = 255; G = 255; B = 255;
                    send_accept = 1;
                    break;
                case "btnblack":
                    R = 0; G = 0; B = 0;
                    send_accept = 1;
                    break;
                case "listBox3_BMPFile_UDP"://发送BMP前 先发送指令=2
                    send_accept = 2;
                    break;  
                default://发送BMP前 先发送指令=2
                    send_accept = 2;
                    break;
            }
            byte flag = 0x7f;
            Int16 DestAddr = 0x0001;//目标地址
            byte Type = 0x02;//指令
            byte Length = 20;
            byte[] cmd = new byte[6 + Length];
            //cmd = { 0x7F, 0x00, 0x01, 0x02, 0x04, 0x01, 0x02, 0x03, 0x04, 0xcc };
            cmd[0] = flag;
            cmd[1] = (byte)(DestAddr >> 8);
            cmd[2] = (byte)(DestAddr);
            cmd[3] = (byte)(Type);
            cmd[4] = (byte)(Length);
            cmd[5] = (byte)(h >> 8);
            cmd[6] = (byte)(h);
            cmd[7] = (byte)(v >> 8);
            cmd[8] = (byte)(v);
            cmd[9] = (byte)(dbv >> 8);
            cmd[10] = (byte)(dbv);
            cmd[11] = (byte)(SPR);
            cmd[12] = (byte)(bit_width);
            cmd[13] = (byte)(bit_64bit_control >> 56);
            cmd[14] = (byte)(bit_64bit_control >> 48);
            cmd[15] = (byte)(bit_64bit_control >> 40);
            cmd[16] = (byte)(bit_64bit_control >> 32);
            cmd[17] = (byte)(bit_64bit_control >> 24);
            cmd[18] = (byte)(bit_64bit_control >> 16);
            cmd[19] = (byte)(bit_64bit_control >> 8);
            cmd[20] = (byte)(bit_64bit_control >> 0);

            cmd[21] = (byte)(R);
            cmd[22] = (byte)(G);
            cmd[23] = (byte)(B);
            cmd[24] = (byte)(send_accept);
            SendCallback(cmd);
        }
        //LED_ON_cmd_  = { 0x7F, 0x00, 0x01, 0x01, 0x01, 0x01, 0xcc };
        //LED_OFF_cmd_ = { 0x7F, 0x00, 0x01, 0x01, 0x01, 0x00, 0xcc };
        int led = 0;

        private void timer_100ms_Tick(object sender, EventArgs e)
        {
            timer_100ms.Enabled = false;
            led++;
            if ((Receive_flag_bit == 1) && (buffer_length == 7)&&(led>4))
            {
                led = 0;
                byte[] binchar = new byte[buffer_length];
                Buffer.BlockCopy(buffer, 0, binchar, 0, buffer_length);
                byte[] bytes = new byte[5];
                Buffer.BlockCopy(buffer, 0, bytes, 0, 5);
                string hexString = BitConverter.ToString(bytes).Replace("-", ""); // 去除分隔符并转换为大写字母形式
                if (hexString == "7F00010101")
                {
                    if (binchar[5] == 0) LED_state.Visible = false;
                    else LED_state.Visible = true;
                    Receive_flag_bit = 0;
                    buffer_length = 0;
                }
            }
            else if((Receive_flag_bit == 1) && (buffer_length == BMP_buffer_length) && (BMP_send_flag == 1))//开启自动下发
            {
                  BMP_send_flag = 0;
                   BMP_buffer_length = 123456789;
                radio_BMP.Checked = true;
                radio_showHEX.Checked = radioButton5.Checked = false;
                button_RX_Click(sender, e);
            }
            if (UDP_Rrogram.UDP_VESA_sign == 3)
            {
                path_2KS = defaultfilePath + "\\IP_out\\DSCoutput";
                IP_out_BMP_path = UDP_Rrogram.UDP_BMP_out_path;
                DirectoryInfo di = new DirectoryInfo(path_2KS);
                CreateListItem(di);//递归加载文件夹里的所有图片
                txtbmp.Text = path_2KS;
                DateTime currentTime = DateTime.Now;
                string tt = "压缩结束" + currentTime.Minute.ToString() + "分；" + currentTime.Second.ToString() + "秒；" + currentTime.Millisecond.ToString() + "毫秒；\r\n";
                ShowMsg(tt);
                send_BMP_2KS(IP_out_BMP_path);
                UDP_Rrogram.UDP_VESA_sign = 1; //开启等待，=2开始压缩，=3压缩完成，=1继续等待，=0不开压缩
                 currentTime = DateTime.Now;
                 tt = "2KS下发完成" + currentTime.Minute.ToString() + "分；" + currentTime.Second.ToString() + "秒；" + currentTime.Millisecond.ToString() + "毫秒；\r\n";
                ShowMsg(tt);
            }
            timer_100ms.Enabled = true;
        }
        private void tabControl1_Click(object sender, EventArgs e)
        {
            if (frmVESADSCTool == null)
            {
                frmVESADSCTool = new DSCToos();//给窗体变量赋值
                frmVESADSCTool.TopLevel = false;
                //frmCMDXm.FormBorderStyle = FormBorderStyle.None;
                //====================================
                frmVESADSCTool.Show();
                //清除之前加载的控件
                //tabPage_DSC.Controls.Clear();
                //加载窗体1控件
                tabPage_DSC.Controls.Add(frmVESADSCTool);
                tabPage_DSC.Text = "DSC-Tool";
                //tabIRC.Hide();
                //ss.TabPages.Remove(tabIRC);
            }
            //ss.SelectedTab = tabADB;
        }



        #endregion

        #region  2KS切灰阶协议
        private void btnPatternW_Click(object sender, EventArgs e)
        {
            if (send_UDP.Checked == true) button_parameter_Click( sender, e);
            else OLED_Show_Click(sender, e);
        }
       
        private void OLED_Show_Click(object sender, EventArgs e)
        {
            byte[] TepArr;
            Button btnTmp = (Button)sender;

                 Send_buf = new byte[25];

                Setting.TempRecord.cmdLen = 25;

                Send_buf[0] = 0x0A; //LCD配置标志
                Send_buf[2] = 0x15; //数据长度
                switch (btnTmp.Name)
                {
                    case "btnPatternW":                             //写入Pattern参数
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = byte.Parse(numPatternR.Value.ToString());
                            Send_buf[4] = byte.Parse(numPatternG.Value.ToString());
                            Send_buf[5] = byte.Parse(numPatternB.Value.ToString());
                        }
                        break;
                    case "btnred":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0;
                        }
                        break; //R
                    case "btngreen":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0;
                        }
                        break; //G
                    case "btnblue":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0xFF;
                        }
                        break; //B
                    case "btnwhite":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0xFF;
                        }
                        break; //W
                    case "btnblack":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0;
                        }
                        break; //BL
                    default:
                        break;
                }

                CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
                try
                {
                    frmTop.comPort.Write(Send_buf, 0, 25);
                }
                catch
                {
                    MessageBox.Show("OLED_Show串口有误，请检查", "错误");
                }
            
        }

        private void checkBox_Gray_ClientSizeChanged(object sender, EventArgs e)
        {
            if (checkBox_Gray.Checked)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternR.Value;
                numPatternG.Enabled = false;
                numPatternB.Enabled = false;
            }
            else
            {
                numPatternG.Enabled = true;
                numPatternB.Enabled = true;
            }
        }

        private void numPatternR_ValueChanged(object sender, EventArgs e)
        {
            if (checkBox_Gray.Checked == true)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternG.Value;
            }
        }
        #endregion

    }

}